#include "stdafx.h"
#include "net/HTTPRequest.hpp"
#include "utils/numberformatter.hpp"
using JHCPP::utils::CNumberFormatter;
#include "charset/ascii.hpp"
#include "charset/string.hpp"
using JHCPP::charset::CAscii;
using JHCPP::charset::icompare;
#include "stdlib/exception.hpp"
using namespace JHCPP::stdlib::jhException;

NET_NAMESPACE_BEGIN

const std::string CHTTPRequest::HTTP_GET            = "GET";
const std::string CHTTPRequest::HTTP_HEAD           = "HEAD";
const std::string CHTTPRequest::HTTP_PUT            = "PUT";
const std::string CHTTPRequest::HTTP_POST           = "POST";
const std::string CHTTPRequest::HTTP_OPTIONS        = "OPTIONS";
const std::string CHTTPRequest::HTTP_DELETE         = "DELETE";
const std::string CHTTPRequest::HTTP_TRACE          = "TRACE";
const std::string CHTTPRequest::HTTP_CONNECT        = "CONNECT";
const std::string CHTTPRequest::HOST                = "Host";
const std::string CHTTPRequest::COOKIE              = "Cookie";
const std::string CHTTPRequest::AUTHORIZATION       = "Authorization";
const std::string CHTTPRequest::PROXY_AUTHORIZATION = "Proxy-Authorization";
const std::string CHTTPRequest::UPGRADE             = "Upgrade";

CHTTPRequest::CHTTPRequest() : m_method(HTTP_GET), m_uri("/")
{
}

CHTTPRequest::CHTTPRequest(const std::string& version)
	: CHTTPMessage(version),
	m_method(HTTP_GET),
	m_uri("/")
{
}

CHTTPRequest::CHTTPRequest(const std::string& method, const std::string& uri) : m_method(method), m_uri(uri)
{
}

CHTTPRequest::CHTTPRequest(const std::string& method, const std::string& uri, const std::string& version)
	: CHTTPMessage(version),
	m_method(method),
	m_uri(uri)
{
}

CHTTPRequest::~CHTTPRequest()
{
}

void CHTTPRequest::setMethod(const std::string& method)
{
	m_method = method;
}

const std::string& CHTTPRequest::getMethod() const
{
	return m_method;
}

void CHTTPRequest::setURI(const std::string& uri)
{
	m_uri = uri;
}

const std::string& CHTTPRequest::getURI() const
{
	return m_uri;
}

void CHTTPRequest::setHost(const std::string& host)
{
	set(HOST, host);
}

void CHTTPRequest::setHost(const std::string& host, UInt16 port)
{
	std::string value;
	if (host.find(':') != std::string::npos)
	{
		// IPv6 address
		value.append("[");
		value.append(host);
		value.append("]");
	}
	else
	{
		value.append(host);
	}    

	if (port != 80 && port != 443)
	{
		value.append(":");
		CNumberFormatter::append(value, port);
	}
	setHost(value);
}

const std::string& CHTTPRequest::getHost() const
{
	return get(HOST);
}

void CHTTPRequest::setCookies(const CNameValueCollection& cookies)
{
	std::string cookie;
	cookie.reserve(64);
	for (CNameValueCollection::ConstIterator it = cookies.begin(); it != cookies.end(); ++it)
	{
		if (it != cookies.begin())
			cookie.append("; ");
		cookie.append(it->first);
		cookie.append("=");
		cookie.append(it->second);
	}
	add(COOKIE, cookie);
}

void CHTTPRequest::getCookies(CNameValueCollection& cookies) const
{
	CNameValueCollection::ConstIterator it = find(COOKIE);
	while (it != end() && icompare(it->first, COOKIE) == 0)
	{
		splitParameters(it->second.begin(), it->second.end(), cookies);
		++it;
	}
}

bool CHTTPRequest::hasCredentials() const
{
	return has(AUTHORIZATION);
}

void CHTTPRequest::getCredentials(std::string& scheme, std::string& authInfo) const
{
	getCredentials(AUTHORIZATION, scheme, authInfo);
}

void CHTTPRequest::setCredentials(const std::string& scheme, const std::string& authInfo)
{
	setCredentials(AUTHORIZATION, scheme, authInfo);
}

bool CHTTPRequest::hasProxyCredentials() const
{
	return has(PROXY_AUTHORIZATION);
}

void CHTTPRequest::getProxyCredentials(std::string& scheme, std::string& authInfo) const
{
	getCredentials(PROXY_AUTHORIZATION, scheme, authInfo);
}

void CHTTPRequest::setProxyCredentials(const std::string& scheme, const std::string& authInfo)
{
	setCredentials(PROXY_AUTHORIZATION, scheme, authInfo);
}

void CHTTPRequest::write(std::ostream& ostr) const
{
	ostr << m_method << " " << m_uri << " " << getVersion() << "\r\n";
	CHTTPMessage::write(ostr);
	ostr << "\r\n";
}

void CHTTPRequest::read(std::istream& istr)
{
	static const int eof = std::char_traits<char>::eof();

	std::string method;
	std::string uri;
	std::string version;
	method.reserve(16);
	uri.reserve(64);
	version.reserve(16);
	int ch = istr.get();
	if (istr.bad()) 
		throw NetException("Error reading HTTP request header");

	if (ch == eof) 
		throw NoMessageException();

	while (CAscii::isSpace(ch)) ch = istr.get();
	if (ch == eof) throw MessageException("No HTTP request header");
	while (!CAscii::isSpace(ch) && ch != eof && method.length() < MAX_METHOD_LENGTH) { method += (char) ch; ch = istr.get(); }
	if (!CAscii::isSpace(ch)) throw MessageException("HTTP request method invalid or too long");
	while (CAscii::isSpace(ch)) ch = istr.get();
	while (!CAscii::isSpace(ch) && ch != eof && uri.length() < MAX_URI_LENGTH) { uri += (char) ch; ch = istr.get(); }
	if (!CAscii::isSpace(ch)) throw MessageException("HTTP request URI invalid or too long");
	while (CAscii::isSpace(ch)) ch = istr.get();
	while (!CAscii::isSpace(ch) && ch != eof && version.length() < MAX_VERSION_LENGTH) { version += (char) ch; ch = istr.get(); }
	if (!CAscii::isSpace(ch)) throw MessageException("Invalid HTTP version string");
	while (ch != '\n' && ch != eof) { ch = istr.get(); }
	CHTTPMessage::read(istr);
	ch = istr.get();
	while (ch != '\n' && ch != eof) { ch = istr.get(); }
	setMethod(method);
	setURI(uri);
	setVersion(version);
}

void CHTTPRequest::getCredentials(const std::string& header, std::string& scheme, std::string& authInfo) const
{
	scheme.clear();
	authInfo.clear();
	if (has(header))
	{
		const std::string& auth = get(header);
		std::string::const_iterator it  = auth.begin();
		std::string::const_iterator end = auth.end();
		while (it != end && CAscii::isSpace(*it)) ++it;
		while (it != end && !CAscii::isSpace(*it)) scheme += *it++;
		while (it != end && CAscii::isSpace(*it)) ++it;
		while (it != end) authInfo += *it++;
	}
	else 
		throw NotAuthenticatedException();
}

void CHTTPRequest::setCredentials(const std::string& header, const std::string& scheme, const std::string& authInfo)
{
	std::string auth(scheme);
	auth.append(" ");
	auth.append(authInfo);
	set(header, auth);
}

NET_NAMESPACE_END
